'use client';

import React, { useState, useEffect } from 'react';
import ExcelViewer from '@/components/ExcelViewer';
import { ParsedExcelFile } from '@/lib/excel-parser.client';
import { Loader2 } from 'lucide-react';

export default function ExcelViewerPage() {
  const [initialData, setInitialData] = useState<ParsedExcelFile | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    // 自动加载项目中的Excel文件
    const loadInitialData = async () => {
      try {
        const response = await fetch('/api/excel');
        if (response.ok) {
          const data = await response.json();
          setInitialData(data);
        } else {
          const errorData = await response.json();
          setError(errorData.error || '加载Excel文件失败');
        }
      } catch (err) {
        setError('网络错误，无法加载Excel文件');
        console.error('加载Excel文件失败:', err);
      } finally {
        setLoading(false);
      }
    };

    loadInitialData();
  }, []);

  if (loading) {
    return (
      <div className="container mx-auto py-8">
        <div className="flex items-center justify-center h-64">
          <div className="text-center">
            <Loader2 className="h-8 w-8 animate-spin mx-auto mb-2" />
            <p className="text-muted-foreground">正在加载Excel数据...</p>
          </div>
        </div>
      </div>
    );
  }

  if (error && !initialData) {
    return (
      <div className="container mx-auto py-8">
        <div className="text-center">
          <h1 className="text-3xl font-bold tracking-tight mb-6">Excel 数据查看器</h1>
          <div className="text-red-500 mb-4">{error}</div>
          <ExcelViewer />
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-8">
      <div className="mb-6">
        <h1 className="text-3xl font-bold tracking-tight mb-2">Excel 数据查看器</h1>
        <p className="text-muted-foreground">
          {initialData 
            ? '石楼油库实体对象与标准对比数据已加载，您也可以上传其他Excel文件' 
            : '上传Excel文件以查看数据内容'
          }
        </p>
      </div>
      
      <ExcelViewer initialData={initialData || undefined} />
    </div>
  );
} 